import os
import hashlib


def calculate_md5(file_path, block_size=65536):
    """计算单个文件的MD5值"""
    md5_hash = hashlib.md5()
    try:
        with open(file_path, "rb") as f:
            # 分块读取大文件，避免内存占用过高
            for block in iter(lambda: f.read(block_size), b""):
                md5_hash.update(block)
        return md5_hash.hexdigest()
    except Exception as e:
        print(f"计算文件 {file_path} 的MD5时出错: {str(e)}")
        return None


def process_jpg_files(output_file="jpg_md5_results.txt"):
    """处理当前目录下所有.jpg文件"""
    # 获取当前工作目录
    current_dir = os.getcwd()
    print(f"正在处理目录: {current_dir}")

    results = []
    # 遍历当前目录中的所有文件
    for filename in os.listdir(current_dir):
        # 检查文件是否以.jpg或.JPG结尾
        if filename.lower().endswith('.jpg'):
            file_path = os.path.join(current_dir, filename)
            # 确保是文件而不是目录
            if os.path.isfile(file_path):
                print(f"正在处理: {filename}")
                md5_value = calculate_md5(file_path)
                if md5_value:
                    results.append((filename, md5_value))

    # 保存结果到文件
    with open(output_file, "w", encoding="utf-8") as f:
        for filename, md5 in results:
            f.write(f"{md5}  {filename}\n")

    print(f"\n处理完成，共计算了 {len(results)} 个JPG文件的MD5值")
    print(f"结果已保存到: {os.path.abspath(output_file)}")


if __name__ == "__main__":
    process_jpg_files()
